import datetime
import os

import pendulum
from apscheduler.schedulers.asyncio import AsyncIOScheduler

from app.core import apscheduler
from app.core.Utils import code_number, now_add_time
from app.core.responses import Response
from app.models.Orders import Orders
from app.models.ServicesScopes import ServicesScopes
from config.config import settings
from schemas.order import Create
from app.services.order_items import OrderItemsServices

scheduler = AsyncIOScheduler()


class OrderServices:
    @staticmethod
    def create(form: Create, uid: int):
        # 生成订单号
        orderid = os.getenv('MCH_ID') + str(pendulum.now().int_timestamp) + code_number(4)
        # 获取服务元素详情
        item = form.order_item
        scope_item = ServicesScopes.find(item.id)
        # 计算总价
        total_amount = 0
        # 判断是否为套餐
        if form.is_menu:
            total_amount = scope_item.price * scope_item.quantity
        else:
            total_amount = scope_item.price * item.scope_quantity
        # 生成订单
        order = {
            "order_number": orderid,
            "uid": uid,
            "total_amount": total_amount,
            "status": "pending",  # 待支付
            "address_id": form.address_id,
            "remark": form.remark,
        }
        # 创建订单
        data = Orders.create(order)
        if data is None:
            # 创建失败
            return Response.message('出问题', '201')
        order_item = {
            "order_id": data.id,
            "quantity": scope_item.quantity,
            "scope_quantity": item.scope_quantity,
            "service_scope_id": item.id,
            "service_id": form.id,
            "price": scope_item.price,
            "total_price": total_amount
        }
        # 创建定时任务
        apscheduler.add_task(orderid, now_add_time(settings.ORDER_TASK_TIME), [data.id])
        # 创建订单元素
        OrderItemsServices.create(order_item)
        return Response.success(data.serialize())

    @staticmethod
    def payment_order(order_id: str, user_id):
        data = Orders.where('uid', user_id).where('id', order_id).where('status', 'pending').first()
        if data is None:
            return Response.failed('订单不存在或已支付')
        data.status = "paid"
        data.save()
        return Response.success(data.serialize())

    @staticmethod
    def get_all(current, size):
        data = Orders.paginate(size, current)
        return data

    @staticmethod
    def get_one(Id: int):
        data = Orders.find(Id)
        return data

    @staticmethod
    def delete(Id):
        data = Orders.find(Id)
        data.delete()
        return data
